<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
    >
      <el-form-item label="数据集类型" prop="datasetTypeName">
        <div>{{ formData.datasetTypeName }}</div>
        <!-- <el-input v-model="formData.datasetTypeName" placeholder="请输入数据集类型" class="gw-input-width-244" disabled /> -->
      </el-form-item>
      <el-form-item label="数据集名称" prop="name">
        <div v-if="formType === 'view'">{{ formData.name }}</div>
        <el-input v-model="formData.name" placeholder="请输入数据集名称" class="gw-input-width-244" v-else />
      </el-form-item>
      <el-form-item :label="formType === 'view' ? 'prompt模板' : '选择prompt模板'" prop="promptId">
        <div v-if="formType === 'view'">{{ formData.promptName }}</div>
        <el-select v-model="formData.promptId" placeholder="请选择" class="gw-input-width-244" filterable v-else>
          <el-option v-for="p in promptData" :key="p.id" :label="p.name" :value="p.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据集描述" prop="remark">
        <div v-if="formType === 'view'">{{ formData.remark }}</div>
        <el-input
          v-model="formData.remark"
          :rows="3"
          type="textarea"
          placeholder="请输入内容"
          maxlength="300"
          show-word-limit
          style="width: 574px"
          v-else
        />
      </el-form-item>
      <el-form-item :label="formType === 'view' ? '评测指标' : '选择评测指标'" prop="indicatorCodes">
        <div v-if="formType === 'view'">{{ indicatorText }}</div>
        <el-transfer v-model="formData.indicatorCodes" :data="indicatorsData" :props="{key: 'code', label: 'name'}" class="transfer-width" v-else>
          <template #default="{ option }">
            <el-tooltip class="item" v-if="option.name.length > 6" effect="dark" :content="option.name" placement="top" >
              <span>{{ option.name }}</span>
            </el-tooltip>
            <span v-else>{{ option.name }}</span>
          </template>
        </el-transfer>
      </el-form-item>
      <el-form-item label="上传文件" v-if="formType === 'create'">
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :file-list="fileList"
          :on-change="handleChange"
          :on-exceed="handleExceed"
          accept=".xlsx, .xls, .csv"
          :limit="1"
          action=""
        >
          <el-button type="primary">
            选取文件
          </el-button>
          <template #tip>
            <div style="font-size: 12px">
              <span>支持 xls、xlsx、csv 格式文件</span>
              <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline; margin-left: 10px;"
              type="primary"
              @click="importTemplate"
            >
              下载模板
            </el-link>
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button @click="submitForm" type="primary">{{  formType === 'create' ?  '新增' : '确定' }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DatasetApi, DatasetVO } from '@/api/multiModel/dataset'
import { PromptApi } from '@/api/multiModel/prompt'
import { IndicatorApi } from '@/api/multiModel/indicator'
import type { UploadProps, UploadFile } from 'element-plus'
import download from '@/utils/download'

/** 数据集 表单 */
defineOptions({ name: 'DatasetForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: '',
  promptId: undefined,
  remark: '',
  datasetTypeId: 0,
  datasetTypeName: '',
  indicatorCodes: undefined,  
  status: undefined,
  num: undefined,
  promptName: ''
})
const formRules = reactive({
  name: [{ required: true, message: '数据集名称不能为空', trigger: 'blur' }],
  promptId: [{ required: true, message: 'promptId不能为空', trigger: 'blur' }],
  indicatorCodes: [{ required: true, message: '评测指标不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const indicatorsData = ref<any[]>([])
const promptData = ref<any[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number, datasetTypeId?: number, datasetTypeName?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type) + '数据集'
  formType.value = type
  resetForm()
  try {
    promptData.value = await PromptApi.getPromptList()
    indicatorsData.value = await IndicatorApi.getIndicatorList()
    if (id) {
      const res = await DatasetApi.getDataset(id)
      const indicatorCodes = res.indicatorCodes.split(",")
      formData.value = res
      formData.value.indicatorCodes = indicatorCodes
      if (type === 'view') {
        getindicatorText(indicatorCodes)
      }
    }
  } finally {
  }
  formData.value = {
    ...formData.value,
    datasetTypeName,
    datasetTypeId,
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const indicatorText = ref('')
const getindicatorText = (codes) => {
  let arr:string[] = []
  codes.forEach(code => {
    let indicator = indicatorsData.value.find(d => d.code === code)
    if (indicator) {
      arr.push(indicator.name)
    }
  })
  indicatorText.value = arr.join(',')
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  try {
    if (formType.value === 'create') {
      const paramData = new FormData()
      const { name, promptId, indicatorCodes = [], remark, datasetTypeId, datasetTypeName } = formData.value
      paramData.append('name', name)
      paramData.append('promptId', promptId + '')
      paramData.append('indicatorCodes', indicatorCodes.join(','))
      paramData.append('remark', remark)
      paramData.append('datasetTypeId', datasetTypeId + '')
      paramData.append('datasetTypeName', datasetTypeName)
      paramData.append('file', fileList.value[0].raw)
      await DatasetApi.createDataset(paramData)
      // message.success(t('common.createSuccess'))
    } else {
      const data = formData.value as unknown as DatasetVO
      const param = data
      param.indicatorCodes = param.indicatorCodes.join(',')
      await DatasetApi.updateDataset(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
  }
}

const fileList = ref<UploadFile[]>([])// 文件列表
const handleChange: UploadProps['onChange'] = (files, uploadFiles) => {
  const fileType = ['xlsx', 'xls', 'csv']
  const fileSize = 20
  let fileExtension = ''
  if (files.name.lastIndexOf('.') > -1) {
    fileExtension = files.name.slice(files.name.lastIndexOf('.') + 1)
  }
  const isImg = fileType.some((type: string) => {
    if (files.name.indexOf(type) > -1) return true
    return !!(fileExtension && fileExtension.indexOf(type) > -1)
  })
  const isLimit = files.size < fileSize * 1024 * 1024
  if (!isImg) {
    message.error(`文件格式不正确, 请上传${fileType.join('/')}格式!`)
  }
  if (!isLimit) {
    message.error(`上传文件大小不能超过${fileSize}MB!`)
  }
  if (!isImg || !isLimit) {
    uploadFiles.splice(0, 1)
    return false
  }
  // message.success('正在上传文件，请稍候...')
  fileList.value.push(files)
}
const handleExceed: UploadProps['onExceed'] = () => {
  const limit = 1
  message.error(`上传文件数量不能超过${limit}个!`)
}

/** 重置表单 */
const resetForm = () => {
  fileList.value = []
  formData.value = {
    id: undefined,
    name: '',
    promptId: undefined,
    promptName: '',
    indicatorCodes: undefined,
    remark: '',
    datasetTypeId: 0,
    num: undefined,
    status: undefined,
    datasetTypeName: '',
  }
  formRef.value?.resetFields()
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await DatasetApi.importDatasetTemplate()
  download.excel(res, '数据集导入模版.xls')
}
</script>
<style lang="scss" scoped>
.transfer-width {
  :deep(.el-transfer-panel) {
    width: 220px; /* 左右两个穿梭框的高度和宽度 */
  }
  :deep(.el-transfer-panel__list) {
    height: 300px
  }
  :deep(.el-transfer__buttons) {
    padding: 0 16px
  }
}
</style>